<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <script>
    // ajax失败重连,重试次数和间隔时间可传入
    function request() {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          // 随机数模拟请求
          let res = Math.random()
          if (res > 0.5) {
            resolve(res)
          } else {
            reject(res)
          }
        })
      })
    }

    /**
     * fun 请求函数
     * time 重试次数
     * delay 重试间隔时间
    */
    function retry(fun, time = 0, delay = 0) {
      return new Promise((resolve, reject) => {
        let inner = async function inner() {
          // 可能会有reject,所以需要使用try/catch
          try {
            const result = await fun()
            resolve(result) // 请求成功
          } catch (error) {
            if (time-- <= 0) {
              // 失败
              reject(error)
            } else {
              console.log(`正在尝试,剩余${time}次`)
              setTimeout(() => {
                inner()
              }, delay)
            }
          }
        }
        // 首次立即调用
        inner()
      })
    }

    retry(request, 3, 2000).then(res => {
      console.log("成功", res)
    }).catch(res => {
      console.log("失败", res);
    })
  </script>
</body>
</html>